#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>
#include <cstring>
#include <unistd.h>
#include <functional>
#include <unordered_map>
#include "Log.hpp"

std::string defaultip = "0.0.0.0";
uint16_t defaultport = 8080;
const int size = 1024;

Log log;

typedef std::function<std::string(const std::string &)> func_t;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

class Server
{
public:
    Server(const uint16_t &port = defaultport, const std::string &_ip = defaultip)
        : _sockfd(0), _ip(defaultip), _isrunning(false), _port(port)
    {
    }
    void Init()
    {
        // 1. 创建udp socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            log(Fatal, "socket create error, sockfd: %d", _sockfd);
            exit(SOCKET_ERR);
        }
        log(Info, "socket create success, sockfd: %d", _sockfd);
        // 2. bind socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);                  // 必须保证端口是网络字节序列的
        local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 字符串转换为unit32_t unit32_t必须也是网络字节序列的
        // local.sin_addr.s_addr = htonl(INADDR_ANY);  任意地址bind 0

        if (bind(_sockfd, (const struct sockaddr *)&local, sizeof(local)) < 0)
        {
            log(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        log(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    }

    void CheckUser(const struct sockaddr_in &client, const std::string clientip, uint16_t clientport)
    {
        auto iter = online_user_.find(clientip);
        if (iter == online_user_.end())
        {
            online_user_.insert({clientip, client});
            std::cout << "[" << clientip << ":" << clientport << "] add to online user." << std::endl;
        }
    }

    void Broadcast(const std::string &info, const std::string clientip, uint16_t clientport)
    {
        for (const auto &user : online_user_)
        {
            std::string message = "[";
            message += clientip;
            message += ":";
            message += std::to_string(clientport);
            message += "]# ";
            message += info;
            socklen_t len = sizeof(user.second);
            sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)(&user.second), len);
        }
    }

    void Run()
    {
        _isrunning = true;
        char inbuffer[size];
        while (_isrunning)
        {
            memset(inbuffer, 0, sizeof(inbuffer));
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                log(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }

            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);
            CheckUser(client, clientip, clientport);

            std::string info = inbuffer;
            Broadcast(info, clientip, clientport);
        }
    }
    ~Server()
    {
        if (_sockfd > 0)
            close(_sockfd);
    }

private:
    int _sockfd;
    std::string _ip;
    bool _isrunning;
    uint16_t _port;
    std::unordered_map<std::string, struct sockaddr_in> online_user_;
};
